import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:intl/intl.dart';
import 'package:mall/constant/string.dart';
import 'package:mall/entity/integral_exchange_entity.dart';
import 'package:mall/page/mine/title_card.dart';
import 'package:mall/service/mine_service.dart';
import 'package:mall/utils/shared_preferences_util.dart';
import 'package:mall/utils/toast_util.dart';
import 'package:mall/widgets/empty_view.dart';

Dio dio = new Dio();

class RecoveryView extends StatefulWidget {
  @override
  _RecoveryViewState createState() => _RecoveryViewState();
}

class _RecoveryViewState extends State<RecoveryView>
    with AutomaticKeepAliveClientMixin {
  ScrollController _scrollController = new ScrollController();
  MineService _mineService = MineService();
  List<ListData> _recoveryList = List();
  var _token;
  var _page = 1;
  var _limit = 10;
  var _total = -1;
  int _beLoad = 0;

  @override
  // void initState() {
  //   super.initState();
  //   SharedPreferencesUtils.getToken().then((value) {
  //     _token = value;
  //     _listRecoveryData();
  //   });
  // }

  @override
  bool get wantKeepAlive => true;

  // 下拉刷新数据
  Future<Null> _refreshData() async {
    _page = 0;
    _listRecoveryData(false);
    print("_refreshData");
  }

  // 上拉加载数据
  Future<Null> _addMoreData() async {
    print("_addMoreData");
    _page++;
    _listRecoveryData(true);
  }

  var token;

  @override
  void initState() {
    super.initState();
    SharedPreferencesUtils.getToken().then((value) {
      token = value;
      _listRecoveryData(true);
    });

    // 首次拉取数据
    _listRecoveryData(true);
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        if (_total > _page * _limit && _total != -1) _addMoreData();
      }
    });
  }

  _listRecoveryData(bool _beAdd) {
    Options options = Options(headers: {});
    options.headers["x-fltmall-token"] = token;
    var parameters = {"page": _page, "limit": _limit};
    _mineService.queryRecovery(parameters, (success) {
      setState(() {
        _total = success.total;
        if (!_beAdd) {
          _recoveryList.clear();
//          posts = result['data'];
          _recoveryList = success.list;
        } else {
//          posts.addAll(result['data']);
          _recoveryList.addAll(success.list);
        }
      });
    }, (error) {
      ToastUtil.showToast(error);
    }, options);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(Strings.MINE_RECOVERY),
        centerTitle: true,
      ),
      body: Container(
        height: double.infinity,
        margin: EdgeInsets.all(ScreenUtil().setWidth(20.0)),
        child: _recoveryList.length == 0
            ? EmptyView()
            : RefreshIndicator(
                onRefresh: _refreshData,
                child: Container(
                  color: Colors.grey[100],
                  child: StaggeredGridView.countBuilder(
                    controller: _scrollController,
                    itemCount: _recoveryList.length,
                    primary: false,
                    crossAxisCount: 4,
                    mainAxisSpacing: 4.0,
                    crossAxisSpacing: 4.0,
                    itemBuilder: (context, index) => TileCard(
                      recovery: _recoveryList[index],
                    ),
                    staggeredTileBuilder: (index) => StaggeredTile.fit(10),
                  ),
                ),
              ),
      ),
    );
    return RefreshIndicator(
      onRefresh: _refreshData,
      child: Container(
        color: Colors.grey[100],
        child: StaggeredGridView.countBuilder(
          controller: _scrollController,
          itemCount: _recoveryList.length,
          primary: false,
          crossAxisCount: 4,
          mainAxisSpacing: 4.0,
          crossAxisSpacing: 4.0,
          itemBuilder: (context, index) => TileCard(
            recovery: _recoveryList[index],
          ),
          staggeredTileBuilder: (index) => StaggeredTile.fit(2),
        ),
      ),
    );
  }

  Widget _recoveryItemView(ListData recovery) {
    return Card(
        child: InkWell(
            onTap: () => _goRecoveryDetail(recovery.fid),
            child: Container(
              margin: EdgeInsets.all(ScreenUtil().setWidth(10.0)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    height: ScreenUtil().setHeight(60.0),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Expanded(
                            child: Container(
                                alignment: Alignment.centerLeft,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(Strings.MINE_RECOVERY_NAME +
                                        "${recovery.fname}"),
                                  ],
                                ))),
                        Padding(
                            padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(5.0))),
                        Expanded(
                            child: Container(
                                alignment: Alignment.centerRight,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(Strings.MINE_RECOVERY_TIME +
                                        _formatTime(recovery)),
                                  ],
                                )))
                      ],
                    ),
                  ),
                  Container(
                    height: ScreenUtil().setHeight(60.0),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Expanded(
                            child: Container(
                                alignment: Alignment.centerLeft,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(Strings.MINE_RECOVERY_FTOTAL_INTEGRAL +
                                        "${recovery.ftotalIntegral ?? "0"}"),
                                  ],
                                ))),
                        Padding(
                            padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(5.0))),
                        Expanded(
                            child: Container(
                                alignment: Alignment.centerRight,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(Strings.MINE_RECOVERY_WIGHT +
                                        "${recovery.fnum}${recovery.funitname}"),
                                  ],
                                )))
                      ],
                    ),
                  ),
                ],
              ),
            )));
  }

  _goRecoveryDetail(int recoveryId) {}

  String _formatTime(ListData recovery) {
    DateTime now = DateTime.parse(recovery.fcreatetime);
    return DateFormat('yyyy-MM-dd').format(now);
  }
}
